
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <cedule/log.h>

#include "config.h"

/**
 * create a config object filled with default values
 */
Config_t * config_create() {
	Config_t * result;

	result = (Config_t*) malloc( sizeof( Config_t ) );
	if ( ! result ) goto error;

	result->host = strdup( "127.0.0.1" ); /* default host */
	result->port = 1100; /* default port */
	result->username = NULL; /* no default user; */
	result->password = NULL; /* no default passwd */
	result->verbose = 0; /* quiet by default */

	return result;

error:
	return NULL;
}

void config_display( Config_t * config )
{
	if ( !config ) {
		printf( " * config : (null)\n");
		return;
	} else {
		printf( " * config:\n" );
		printf( "   * host : %s\n", config->host );
		printf( "   * port : %d\n", config->port );
		printf( "   * username : %s\n", config->username );
		printf( "   * password : %s\n", config->password );
		printf( "   * verbose : %d\n", config->verbose );	
	}
}

void config_usage( const char * exec_name )
{
	printf("Usage: %s [options]\n", exec_name);
	/*	printf("  -c <file>       use given configuration file\n");  */
	printf("  -u <username>   set username\n"); 
	printf("  -k <password>   set key\n"); 
	printf("  -a <host>       set host address (localhost by default)\n"); 
	printf("  -p <port>       set port (1100 by default)\n"); 
	printf("  -v              verbose mode (disabled by default)\n");
	printf("  -h              this help\n"); 
}


/**
 * destroy config object and free memory
 */
void config_destroy( Config_t * config ) 
{
	if ( config )
		free( config );
}


/**
 * check that all parameters are coherent 
 */
int config_is_valid( Config_t * config ) 
{
	/* FIXME: should really validate config parameters instead of sending fake values */
	return 1;
}

int config_parse_cmdline( Config_t* config, int argc, char** argv) 
{
	int opt;

	if ( !config )
		return -1;

	while ((opt = getopt(argc, argv, "u:k:p:a:hfv")) != -1) {
		switch(opt) {

			case 'h':
				config_usage( argv[0] );
				break;

			case 'a':
				if ( !optarg )
					goto error;
				if ( config->host ) free( config->host );
				config->host = strdup( optarg );
				break;

			case 'p':
				if ( !optarg )
					goto error;
				config->port = atoi( optarg );
				break;

			case 'u':
				if ( !optarg )
					goto error;
				if ( config->username) free( config->username );
				config->username = strdup( optarg );

				break;

			case 'k':
				if ( !optarg )
					goto error;
				if ( config->password) free( config->password );
				config->password = strdup( optarg );
				break;

			case 'v':
				config->verbose = 1;
				log_verbosity = 1;
				break;

			default:
				log_error( "Bad argument %c\n", opt );
		}
	}

	return 0;

error:
	config_usage( argv[0] );
	return -1;
}
